package com.leiduoduo.oms.controller;

import com.auth0.jwt.JWT;
import com.google.gson.JsonObject;
import com.leiduoduo.oms.annotation.PassToken;
import com.leiduoduo.oms.annotation.UserLoginToken;
import com.leiduoduo.oms.pojo.Dinner;
import com.leiduoduo.oms.pojo.Table;
import com.leiduoduo.oms.pojo.User;
import com.leiduoduo.oms.service.DinnerService;
import com.leiduoduo.oms.service.TableService;
import com.leiduoduo.oms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@CrossOrigin
public class DinnerController {
    @Autowired
    DinnerService dinnerService;
    @Autowired
    TableService tableService;
    @Autowired
    UserService userService;

    @PostMapping("/addDinner")
    @PassToken
    public boolean addDinner(Dinner dinner){
        return dinnerService.addDinner(dinner);
    }
    @PostMapping("/delDinner")
    @UserLoginToken
    public boolean delDinner(Dinner dinner){
        return dinnerService.delDinner(dinner);
    }
    @PostMapping("/upDinner")
    @UserLoginToken
    public boolean upDinner(Dinner dinner){
        return dinnerService.upDinner(dinner);
    }
    @GetMapping("/getDinnerById/{id}")
    @UserLoginToken
    public Dinner getDinnerById(@PathVariable("id") String id){
        return dinnerService.getDinnerByCode(id);
    }
    @GetMapping("/getDinnerList")
    @UserLoginToken
    public List<Dinner> getDinnerList(){
        return dinnerService.getDinnerList();
    }
    @PostMapping("/startDinner")
    @PassToken
    public Map<String, Object> startDinner(@RequestBody Map<String, Object> map, HttpServletRequest request){
        /*
        {
        userInfo:{name:123,avatar:url} //拿来更新用户信息的
        dinner:{table_id:12,people_number:12,note:'xxxx'}
        }
         */
        String token = request.getHeader("Authorization");
        String[] tokens =token.split(" ");
        token = tokens[1];
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();
        Map<String, Object> dinner = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        userInfo = (HashMap<String, Object>)map.get("userInfo");
        dinner = (HashMap<String, Object>)map.get("dinner");
        String name = userInfo.get("name").toString();
        String avatar = userInfo.get("avatar").toString();
        String appCode = JWT.decode(token).getAudience().get(0);
        int table_id = (int)dinner.get("table_id");
        int people_number = (int)dinner.get("people_number");
        String note = dinner.get("note").toString();
        Dinner dinner1 = new Dinner();
        dinner1.setTable_id(table_id);
        dinner1.setPeople_number(people_number);
        dinner1.setNote(note);
        long dinnerCodel = System.currentTimeMillis();
        String dinnerCode = dinnerCodel+""+table_id;
        dinner1.setDinner_code(dinnerCode);
        //user信息修改
        User user1 = new User();
        user1.setName(name);
        user1.setAvatar(avatar);
        user1.setApp_code(appCode);
        userService.upUserMsg(user1);
        //获取桌子当前状态
        int tablestate = tableService.getTableById(table_id).getState();
        //如果当前状态为0（空闲）则将桌子状态改为1，并添加一个dinner与桌子绑定
        if (tablestate == 0){
            Table table = new Table();
            dinnerService.addDinner(dinner1);
            tableService.startDinner(table.setCurrent_dinner_id(dinnerCode).setCaptcha(String.format("%04d",new Random().nextInt(9999))).setId(table_id));
            data.put("dinner_code",dinner1.getDinner_code());
            data.put("status","success");
            data.put("captcha",table.getCaptcha());
            result.put("data",data);
            result.put("errorcode",0);
            result.put("msg","success");
        } else{
            data.put("dinner_code",dinner1.getDinner_code());
            data.put("status","error");
            data.put("captcha",null);
            result.put("data",data);
            result.put("errorcode",0);
            result.put("msg","该桌子已被占用");
        }
        return result;
    }
    @PostMapping("/validateCaptcha")
    @PassToken
    public Map<String, Object> validateCaptcha(@RequestBody Map<String, Object> map){
        Map<String, Object> result = new HashMap<>();
        System.out.println(map);
        //得到前端传来的密码
        String captchar = (String)map.get("captcha");
        //得到前端传来的桌子编码
        int table_id = (int)map.get("table_id");
        //通过桌子编码查询桌子
        Table table = tableService.getTableById(table_id);
        //同坐桌子中存储的dinnercode查询dinner
        Dinner dinner = dinnerService.getDinnerByCode(table.getCurrent_dinner_id());
        if (captchar.equals(table.getCaptcha()) ) {
            result.put("data",dinner);
            result.put("errorcode",0);
            result.put("msg","success");
        } else{
            result.put("data",null);
            result.put("errorcode",422);
            result.put("msg","验证码错误");
        }
        return result;
    }

}
